<?php

class AppController extends Controller
{
	var $isAdmin;
	var $userID;
	var $coreUrl;

    function checkLock()
    {
        if(defined('DB_LOCKED') && DB_LOCKED == 1)
        {
            $this->flash('Database locked', '/');
            exit();
        }
    }
	
	function flash($message, $url, $delay = QDB_FLASH_DELAY)
	{
	    $this->Session->setFlash($message);
	    $this->redirect($url);
	    exit();
	}

	function isLoggedIn()
	{
		return $this->Session->check('openid');
	}
	
	function getIdentity()
	{
		if(!$this->isLoggedIn())
			return null;
	
		return $this->Session->read('openid');
	}
	
	function checkRights()
	{
    	if(!$this->isAdmin)
    	{
            $this->flash('You do not have the required permissions to access this page.', '/');
            exit();
        }
   	}
	
	function checkLoggedIn()
	{
	    if(!$this->isLoggedIn())
	    {
		$this->flash('You must be logged in to use this function.', '/');
	    }
	}
	
	function getUserIP()
	{
	    return $_SERVER['REMOTE_ADDR'];
	}
	
	function beforeFilter()
	{
	    if((!defined('DB_LOCKED') || DB_LOCKED != 1) && ereg('https?://', $this->referer()))
	    {
	        App::import('Model', 'Visit');
	        $visit = new Visit();
	        $visit->save(array('Visit' =>
	    	    array('ip' => $this->getUserIP(), 'referer' => $this->referer(), 'url' => $_SERVER['REQUEST_URI'])));
	    }
								
		App::import('Model', 'User');
		$user = new User();
		$users = $user->findByName($this->getIdentity());
		
		if($users == null)
		{
		    $this->userID = -1;
		    $this->isAdmin = false;
		}
		else
		{
		    $this->userID = $users['User']['id'];
		    $this->isAdmin = $users['User']['access'] == 1;
		}
		
		$this->set('loggedIn', $this->isLoggedIn());
		$this->set('openID', $this->getIdentity());
		$this->set('isAdmin', $this->isAdmin);
		
		$this->coreUrl = 'http://' . $_SERVER['SERVER_NAME'] . $this->webroot;
	}
	
	function getCoreUrl()
	{
    	    return $this->coreUrl;
	}
	
	function getUserID()
	{
	    if(!$this->isLoggedIn())
		return -1;
	
	    if($this->userID != -1)
		return $this->userID;
	
	    $user = new User();
	    $userrec = array('User' => array('name' => $this->getIdentity(), 'access' => 0));
	    
	    if($user->save($userrec))
	    {
		$this->userID = $user->id;
	    }
	    
	    return $this->userID;
	}
}

?>
